import { defineStore } from 'pinia'
import { getDictionary } from '@/api/sys/dictionary'
import { releaseLock, requestLock } from '@/plugins/lock'

type Dictionary = {
  dictionaryCode: string
  dictionaryValue: string
}

const useDictionaryStore = defineStore('Dictionary', {
  state: () => ({
    map: new Map<string, Dictionary[]>(),
  }),
  actions: {
    async getDictionary(parentDictionaryValue: string) {
      await requestLock()
      try {
        if (this.map.has(parentDictionaryValue)) {
          return
        }
        const { data } = await getDictionary(parentDictionaryValue)
        if (data.status) {
          this.map.set(parentDictionaryValue, data.data)
        }
      } finally {
        releaseLock()
      }
    },
    getDictionaryCode(parentDictionaryValue: string, dictionaryValue: string) {
      return this.map
        .get(parentDictionaryValue)
        ?.find((item: any) => item.dictionaryValue === dictionaryValue)
        ?.dictionaryCode
    },
    getDictionaryValue(parentDictionaryValue: string, dictionaryCode: string) {
      return this.map
        .get(parentDictionaryValue)
        ?.find((item: any) => item.dictionaryCode === dictionaryCode)
        ?.dictionaryValue
    },
    reset(key?: string) {
      if (key) {
        this.map.delete(key)
      } else {
        this.map.clear()
      }
    },
  },
  getters: {},
})

export default useDictionaryStore
